package com.yc.supermarket.web.controller;

import com.yc.supermarket.entity.Commodity;
import com.yc.supermarket.entity.ProductType;
import com.yc.supermarket.service.CommodityService;
import com.yc.supermarket.service.ProductTypeService;
import com.yc.supermarket.service.impl.CommodityServiceImpl;
import com.yc.supermarket.service.impl.ProductTypeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.UUID;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/addGoods")
@MultipartConfig
public class addGoodsController extends BaseController {

    private CommodityService service = new CommodityServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String op=req.getParameter("op");
        if("findAll".equals(op)){
            doFindAll(req,resp);
        }else if("findByTrem".equals(op)){
            doFindByTrem(req,resp);
        }else if("findTotal".equals(op)){
            doFindTotal(req,resp);
        }else if("findTotalByTrem".equals(op)){
            doFindTotalByTrem(req,resp);
        }else if("updatePromo".equals(op)){
            doUpdatePromo(req,resp);
        }else if("deleteCommodityById".equals(op)){
            doDeleteCommodityById(req,resp);
        }else  if("updateStatus".equals(op)){
            doUpdateStatus(req,resp);
        }else if("addCommodity".equals(op)){
            doAddCommodity(req,resp);
        }else if("modify".equals(op)){
            doModify(req,resp);
        }else{
            printToJson(resp,"No method.....405");
        }
    }

    protected void doFindAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String,Object> map = service.findAll();
        System.out.println(map);
        printToJson(resp,map);
    }

    protected void doFindByTrem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String,Object> map = parseRequest(req);
        Map<String,Object> resultmap = service.findByTrem(map);
        System.out.println("****"+resultmap);
        printToJson(resp,resultmap);
    }

    protected void doFindTotal(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int total = service.findTotal();
        printToJson(resp,total);
    }

    protected void doFindTotalByTrem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String,Object> map = parseRequest(req);
        int total = service.findTotalByTrem(map);
        printToJson(resp,total);

    }

    protected void doUpdatePromo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String,Object> map = parseRequest(req);
        int result = service.updatePromo(map);
        System.out.println("***doUpdatePromo"+map);
        printToJson(resp,result);
    }

    protected void doDeleteCommodityById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("commodityId");
        int result = service.deleteCommodityById(id);
        printToJson(resp,result);
    }

    protected void doUpdateStatus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Commodity commodity = parseRequest(req,Commodity.class);
        boolean result = service.updateStatus(commodity);
        printToJson(resp,result);
    }

    protected void doModify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StringBuilder imagePathBuilder = upload(req, resp);
        Commodity commodity = new Commodity();
        if (imagePathBuilder!=null && imagePathBuilder.length()>0){
            commodity.setCommodityPic(imagePathBuilder.toString());
        }else{
            System.out.println("***&&&***nonono");
        }
        if (req.getParameter("commodityId") != null){
            commodity.setCommodityId(Integer.parseInt(req.getParameter("commodityId")));
        }if (req.getParameter("commodityName") != null){
            commodity.setCommodityName(req.getParameter("commodityName"));
        }if (req.getParameter("typeId") != null){
            commodity.setTypeId(Integer.parseInt(req.getParameter("typeId")));
        }if (req.getParameter("price") != null){
            commodity.setPrice(new BigDecimal(req.getParameter("price")));
        }if (req.getParameter("allowDiscount") != null){
            commodity.setAllowDiscount(Integer.parseInt(req.getParameter("allowDiscount")));
        }if (req.getParameter("stockAlarmQuantity") != null){
            commodity.setStockAlarmQuantity(Integer.parseInt(req.getParameter("stockAlarmQuantity")));
        }if (req.getParameter("allowSale") != null){
            commodity.setAllowSale(Integer.parseInt(req.getParameter("allowSale")));
        }
        System.out.println(commodity);
        boolean result = service.modifyCommodity(commodity);
        printToJson(resp,result);
    }

    protected void doAddCommodity(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StringBuilder imagePathBuilder = upload(req, resp);

        Commodity commodity = new Commodity();
        commodity.setCommodityPic(imagePathBuilder.toString());
        if (req.getParameter("commodityId") != null){
            commodity.setCommodityId(Integer.parseInt(req.getParameter("commodityId")));
        }if (req.getParameter("commodityName") != null){
            commodity.setCommodityName(req.getParameter("commodityName"));
        }if (req.getParameter("typeId") != null){
            commodity.setTypeId(Integer.parseInt(req.getParameter("typeId")));
        }if (req.getParameter("price") != null){
            commodity.setPrice(new BigDecimal(req.getParameter("price")));
        }if (req.getParameter("allowDiscount") != null){
            commodity.setAllowDiscount(Integer.parseInt(req.getParameter("allowDiscount")));
        }if (req.getParameter("stockQuantity") != null){
            commodity.setStockQuantity(Integer.parseInt(req.getParameter("stockQuantity")));
        }if (req.getParameter("stockAlarmQuantity") != null){
            commodity.setStockAlarmQuantity(Integer.parseInt(req.getParameter("stockAlarmQuantity")));
        }if (req.getParameter("allowSale") != null){
            commodity.setAllowSale(Integer.parseInt(req.getParameter("allowSale")));
        }if (req.getParameter("manufacturerId") != null){
            commodity.setManufacturerId(Integer.parseInt(req.getParameter("manufacturerId")));
        }if (req.getParameter("supplierId") != null){
            commodity.setSupplierId(Integer.parseInt(req.getParameter("supplierId")));
        }
        System.out.println(commodity);
        boolean result = service.addCommodity(commodity);
        printToJson(resp,result);
    }

    private StringBuilder upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        第一部分:将多图片保存在本地磁盘
        // 获取所有上传的文件部分
        Collection<Part> parts = req.getParts();
//        存储多张图片路径的参数
        StringBuilder imagePathBuilder = new StringBuilder();
        // 遍历所有文件部分
        for (Part part : parts) {
            // 获取上传文件的名称
            String submittedFileName = getSubmittedFileName(part);
            System.out.println("submittedFileName = " + submittedFileName);
            // 生成唯一的文件名，防止文件名冲突
            if(submittedFileName!=null){
                String extname = submittedFileName.substring(submittedFileName.lastIndexOf("."));
                String newFileName = UUID.randomUUID().toString() + extname;
                String savePath = "D:/software/apache-tomcat-9.0.43/webapps/supermarket_pics/";
                File file = new File(savePath + newFileName);

                // 将上传的文件保存到本地磁盘
                try (InputStream inputStream = part.getInputStream();
                     FileOutputStream outputStream = new FileOutputStream(file)) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 构造图片路径并追加到StringBuilder
                String imagePath = "../../supermarket_pics/" + newFileName;
                imagePathBuilder.append(imagePath).append(";");
            }
        }

        // 删除最后一个逗号
        if (imagePathBuilder.length() > 0) {
            imagePathBuilder.deleteCharAt(imagePathBuilder.length() - 1);
        }
        System.out.println(imagePathBuilder.toString());
        return imagePathBuilder;
    }

    private String getSubmittedFileName(Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }


}
